//
//  AlertHandler.swift
//  
//
//  Created by 孙长坦 on 2022/6/16.
//

import Foundation
import WebKit
import LibBase


class AlertHandler: WebViewHandlerProtocol {
    static var id: String = "alert"
    
    
    func handler(_ handler: WebViewHandlerProtocol,
                 webView: WKWebViewEx?,
                 frameInfo: WKFrameInfo,
                 params: [String: Any]?) {
        guard let webView = webView else {
            return
        }

        guard let params = params,
              let uuid = params["uuid"] as? String else {
            return
        }
        
        let message = params["message"] as? String ?? ""
        
        Dialog.shared.alert(title: "提示", message: message) { [weak self] buttonId in
            let result: String?
            if let data = try? CodableBuilder().createJSONEncoder().encode(["action": buttonId ?? ""]) {
                result = String(data: data, encoding: .utf8)
            } else {
                result = nil
            }
            
            self?.runSuccessCallback(webView: webView,
                                     uuid: uuid, code: 0, message: "alert:ok",
                                     data: result, handlerParams: params)
        }
    }
}
